<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :search.sync="search"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.info_delete"
                   @click="handleDelete">删除
        </el-button>
        <!--        <el-button type="danger"-->
        <!--                   size="small"-->
        <!--                   icon="el-icon-delete"-->
        <!--                   plain-->
        <!--                   @click="handleCron">Cron表达式-->
        <!--        </el-button>-->
      </template>
      <!--      <template slot-scope="{type,size}" slot="menu" >-->
      <template slot-scope="scope" slot="menu">
        <el-dropdown @command="handleCommand">
          <el-button :size="scope.size" :type="scope.type">运行状态<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item :command="beforeHandleCommand('start', scope)">启动</el-dropdown-item>
            <el-dropdown-item :command="beforeHandleCommand('stop', scope)">停止</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

        <el-dropdown @command="handleCommand">
          <el-button :size="scope.size" :type="scope.type">自定义操作<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <!--            <el-dropdown-item v-on:click.native="triggerOnce(scope)">执行一次</el-dropdown-item>-->
            <el-dropdown-item :command="beforeHandleCommand('trigger', scope)">执行一次</el-dropdown-item>
            <el-dropdown-item :command="beforeHandleCommand('querylog', scope)">查询日志</el-dropdown-item>
            <el-dropdown-item :command="beforeHandleCommand('register', scope)">注册节点</el-dropdown-item>
            <el-dropdown-item :command="beforeHandleCommand('nextexectime', scope)">下次执行时间</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

        <!--        <el-dropdown>-->
        <!--          <el-button :size="scope.size" :type="scope.type">代码<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>-->
        <!--          </el-button>-->
        <!--          <el-dropdown-menu slot="dropdown">-->
        <!--            <el-dropdown-item>GLUE IDE</el-dropdown-item>-->
        <!--          </el-dropdown-menu>-->
        <!--        </el-dropdown>-->
      </template>
    </avue-crud>
    <el-dialog title="Cron表达式" :visible.sync="openCron" append-to-body destroy-on-close class="scrollbar">
      <crontab @hide="openCron=false" v-model="expression"></crontab>
      <span slot="footer" class="dialog-footer">
        <el-button @click="openCron=false">取 消</el-button>
        <el-button type="primary" @click="handleCron2ok">确 定</el-button>
      </span>
    </el-dialog>
    <!--    <el-dialog title="Cron表达式" :visible.sync="openResister" append-to-body destroy-on-close class="scrollbar">-->
    <!--      <crontab @hide="openResister=false" :register="register"></crontab>-->
    <!--    </el-dialog>-->

    //以下对话框显示注册节点的信息
    <el-dialog title="注册节点" :visible.sync="openResister" width="25%" center append-to-body destroy-on-close
               class="scrollbar">
      <el-table :data="registryListData" size="mini" border>
        <el-table-column
          prop="index"
          label="序号"
          width="60">
        </el-table-column>
        <el-table-column
          prop="address"
          label="地址">
        </el-table-column>
      </el-table>
    </el-dialog>

    //以下对话框显示下次执行时间的信息
    <el-dialog title="下次执行时间" :visible.sync="openNextExecTime" width="25%" center append-to-body destroy-on-close
               class="scrollbar">
      <el-table :data="nextExecTimeListData" size="mini" border>
        <el-table-column
          prop="nextTime"
          label="执行时间">
        </el-table-column>
      </el-table>
    </el-dialog>

  </basic-container>
</template>

<script>
  import {
    getList,
    getDetail,
    add,
    update,
    remove,
    trigger,
    getRegister,
    getNextExecTime,
    taskStart,
    taskStop
  } from "@/api/job/task";
  import {mapGetters} from "vuex";
  import crontab from '@/components/crontab'

  export default {
    components: {crontab},
    data() {
      return {
        form: {},
        search: {},
        query: {},
        // 是否显示Cron表达式弹出层
        openCron: false,
        // 传入的表达式
        expression: "",
        openResister: false, //注册节点对话框
        registryListData: [],
        openNextExecTime: false, //下次执行事件对话框
        nextExecTimeListData: [],
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          // calcHeight: 210,
          searchShow: true,
          searchMenuSpan: 6,

          // menuType: "menu",
          menuBtn: true,
          menuBtnTitle: "menuBtnTitle",
          menuTitle: "其他",
          // copyBtn: true,


          addBtn: true,
          tip: false,
          border: true,
          index: false,
          viewBtn: true,
          selection: true,
          column: [
            {
              label: "序号",
              prop: "id",
              search: false,
              addDisplay: false,
            },
            {
              label: "执行器",
              prop: "jobGroup",
              search: true,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "任务描述",
              prop: "jobDesc",
              search: true,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "负责人",
              prop: "author",
              search: false,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            }, {
              label: "报警邮件",
              prop: "alarmEmail",
              search: false,
              showColumn: false,
            },
            {
              label: "调度类型",
              prop: "scheduleType",
              search: true,
              type: "select",
              dicData: [{
                label: '无',
                value: "NONE"
              },{
                label: 'CRON',
                value: "CRON"
              }, {
                label: '固定速度',
                value: "FIX_RATE"
              }],
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "调度配置",
              prop: "scheduleConf",
              search: false,
              type: "input",
              click: (data) => {
                this.handleCron2(data)
              },
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "运行模式",
              prop: "glueType",
              search: false,
              type: "select",
              dicData: [{
                label: 'BEAN',
                value: "BEAN"
              },{
                label: 'GLUE(Java)',
                value: "GLUE_GROOVY"
              },{
                label: 'GLUE(Shell)',
                value: "GLUE_SHELL"
              },{
                label: 'GLUE(Python)',
                value: "GLUE_PYTHON"
              },{
                label: 'GLUE(PHP)',
                value: "GLUE_PHP"
              },{
                label: 'GLUE(Nodejs)',
                value: "GLUE_NODEJS"
              }, {
                label: 'GLUE(PowerShell)',
                value: "GLUE_POWERSHELL"
              }],
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "JobHandler",
              prop: "executorHandler",
              search: false,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            }, {
              label: "任务参数",
              prop: "executorParam",
              search: false,
              showColumn: false,
            },
            {
              label: "状态0停止，1运行",
              prop: "triggerStatus",
              search: false,
              addDisplay: false,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            }, {
              label: "路由策略",
              prop: "executorRouteStrategy",
              search: false,
              showColumn: false,
              type: "select",
              dicData: [{
                label: '第一个',
                value: "FIRST"
              }, {
                label: '最后一个',
                value: "LAST"
              }, {
                label: '轮询',
                value: "ROUND"
              }, {
                label: '随机',
                value: "RANDOM"
              }, {
                label: '一致性HASH',
                value: "CONSISTENT_HASH"
              }, {
                label: '最不经常使用',
                value: "LEAST_FREQUENTLY_USED"
              }, {
                label: '最近最久未使用',
                value: "LEAST_RECENTLY_USED"
              }, {
                label: '故障转移',
                value: "FAILOVER"
              }, {
                label: '忙碌转移',
                value: "BUSYOVER"
              }, {
                label: '分片广播',
                value: "SHARDING_BROADCAST"
              }],
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            }, {
              label: "子任务ID*",
              prop: "childJobId",
              search: false,
              showColumn: false,
            }, {
              label: "调度过期策略*",
              prop: "misfireStrategy",
              search: false,
              showColumn: false,
              type: "select",
              dicData: [{
                label: '忽略',
                value: "DO_NOTHING"
              }, {
                label: '立即执行一次',
                value: "FIRE_ONCE_NOW"
              }],
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            }, {
              label: "阻塞处理策略*",
              prop: "executorBlockStrategy",
              search: false,
              showColumn: false,
              type: "select",
              dicData: [{
                label: '单机串行',
                value: "SERIAL_EXECUTION"
              }, {
                label: '丢弃后续调度',
                value: "DISCARD_LATER"
              }, {
                label: '覆盖之前调度',
                value: "COVER_EARLY"
              }],
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            }, {
              label: "任务超时时间*",
              prop: "executorTimeout",
              search: false,
              showColumn: false,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            }, {
              label: "失败重试次数*",
              prop: "executorFailRetryCount",
              search: false,
              showColumn: false,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
          ]
        },
        data: [],
      };
    },
    watch: {
      expression(old, newval) {
        console.log(old)
        console.log(newval)
      }
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.jobexecutor_add, false),
          viewBtn: this.vaildData(this.permission.jobexecutor_view, false),
          delBtn: this.vaildData(this.permission.jobexecutor_delete, false),
          editBtn: this.vaildData(this.permission.jobexecutor_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      rowSave(row, done, loading) {
        add(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleCron2(data) {
        console.log("handleCron2")
        this.expression = this.form.scheduleConf;
        this.openCron = true;
      },
      handleCron2ok() {
        console.log("handleCron2ok")
        this.form.scheduleConf = this.expression;
        this.openCron = false;

      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage) {
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
      },

      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      beforeHandleCommand(type, row) {
        return {
          type,
          row
        }
      },
      handleCommand(command) {
        let type = command.type
        let scope = command.row
        let that = this;
        switch (type) {
          case "trigger":
            trigger(scope.row.id, scope.row.executorParam, scope.row.jobGroup).then(res => {
              console.log(res);
            })
            break;
          case "querylog":
            break;
          case "register":
            that.openResister = true
            that.registryListData = []
            // registryListData
            getRegister(scope.row.id).then(res => {
              console.log(res);
              let registryList = res.data.data.registryList;
              for (let i = 0; i < registryList.length; i++) {
                that.registryListData.push({"index": i, "address": registryList[i]})
              }
              console.log("registryListData")
            });
            break;
          case "nextexectime":
            console.log("nextexectime");
            that.openNextExecTime = true
            that.nextExecTimeListData = []
            //nextTime

            getNextExecTime(scope.row.scheduleType, scope.row.scheduleConf).then(res => {
              console.log(res);
              let nextTimeList = res.data.data;
              for (let i = 0; i < nextTimeList.length; i++) {
                that.nextExecTimeListData.push({"nextTime": nextTimeList[i]})
              }
              console.log("registryListData")

            })
            break;
          case "start":
            taskStart(scope.row.id).then(res => {
              console.log(res);
            })
            break;
          case "stop":
            taskStop(scope.row.id).then(res => {
              console.log(res);
            })
            break
          default:
            break
        }

      },
      // triggerOnce(scope) {
      //   console.log("triggerOnce")
      //   console.log(scope)
      //
      //   trigger(scope.row.id, scope.row.executorParam, scope.row.jobGroup).then(res => {
      //     console.log(res);
      //   })
      // },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data;
          this.page.total = data.count;
          this.data = data.data;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
